package com.nodecollege.cloud.service.impl;

import com.nodecollege.cloud.common.constants.RedisConstants;
import com.nodecollege.cloud.common.exception.NCException;
import com.nodecollege.cloud.common.utils.RedisUtils;
import com.nodecollege.cloud.service.MailSendService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
import java.io.File;
import java.util.List;

/**
 * @类名: MailSender<br>
 * @描述: 邮件发送<br>
 */
@Slf4j
@Service
public class MailSendServiceImpl implements MailSendService {

    @Autowired
    JavaMailSender mailSender;

    //发件人名称设置
    @Value("${spring.mail.username}")
    private String sendUser;

    @Autowired
    private RedisUtils redisUtils;

    @Override
    public void sendEmailCert(String email, String cert) {
        Long ex = redisUtils.getExpire(RedisConstants.EMAIL_CERT + email);
        if (ex != null && ex > 60 * 4) {
            throw new NCException("", "已经发送邮件，请稍后再发！");
        }
        sendEmail(email, "验证码-节点学院", "您的验证码为 " + cert + " （有效期5分钟）");
        redisUtils.set(RedisConstants.EMAIL_CERT + email, cert, 5 * 60);
    }

    @Override
    public Boolean checkEmailCert(String email, String cert) {
        String exCert = redisUtils.get(RedisConstants.EMAIL_CERT + email, String.class);
        if (null == cert || !cert.equalsIgnoreCase(exCert)) {
            return false;
        }
        return true;
    }

    @Override
    public void delEmailCert(String email) {
        redisUtils.delete(RedisConstants.EMAIL_CERT + email);
    }

    @Override
    public void sendEmail(String toMail, String title, String content) {
        final MimeMessage mimeMessage = mailSender.createMimeMessage();
        final MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
        try {
            message.setFrom(sendUser);
            message.setTo(toMail);
            message.setSubject(title);
            message.setText(content + "\n\n\n节点学院");
        } catch (MessagingException e) {
            log.error("发送邮件失败！格式问题。", e);
            throw new NCException("", "发送邮件失败！格式问题。");
        }
        mailSender.send(mimeMessage);
    }

    /**
     * @param toMail  收件人，多个用英文格式逗号分隔
     * @param replyTo 抄送人，多个用英文格式逗号分隔
     * @param title   邮件主题
     * @param content 邮件内容
     * @param files   附件
     * @throws Exception
     * @方法名: sendSimpleMail<br>
     * @描述: 发送普通文本格式的邮件<br>
     */
    @Override
    public void sendSimpleMail(String toMail, String replyTo, String title, String content, List<File> files) {
        final MimeMessage mimeMessage = mailSender.createMimeMessage();
        try {
            final MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom(sendUser);
            helper.setSubject(title);
            helper.setText(content);

            //设置多个收件人
            String[] toAddress = toMail.split(",");
            helper.setTo(toAddress);

            //设置多个抄送
            if (StringUtils.isNotBlank(replyTo)) {
                //helper.setReplyTo(replyTo);
                InternetAddress[] internetAddressCC = InternetAddress.parse(replyTo);
                mimeMessage.setReplyTo(internetAddressCC);
            }

            //添加附件
            if (null != files) {
                for (File file : files) {
                    helper.addAttachment(file.getName(), file);
                }
            }
        } catch (MessagingException e) {
            log.error("发送邮件失败！格式问题。", e);
            throw new NCException("", "发送邮件失败！格式问题。");
        }
        mailSender.send(mimeMessage);
    }

    /**
     * @param toMail      收件人，多个用英文格式逗号分隔
     * @param replyTo     抄送人，多个用英文格式逗号分隔
     * @param title       邮件主题
     * @param htmlContent 邮件内容
     * @param files       附件
     * @throws Exception
     * @方法名: sendHtmlMail<br>
     * @描述: 发送HTML格式的邮件<br>
     */
    @Override
    public void sendHtmlMail(String toMail, String replyTo, String title, String htmlContent, List<File> files) {
        final MimeMessage mimeMessage = mailSender.createMimeMessage();
        try {
            final MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom(sendUser);
            helper.setSubject(title);
            helper.setText(htmlContent, true);

            //设置多个收件人
            String[] toAddress = toMail.split(",");
            helper.setTo(toAddress);

            //设置多个抄送
            if (StringUtils.isNotBlank(replyTo)) {
                //helper.setReplyTo(replyTo);
                InternetAddress[] internetAddressCC = InternetAddress.parse(replyTo);
                mimeMessage.setRecipients(RecipientType.CC, internetAddressCC);
            }

            //添加附件
            if (null != files) {
                for (File file : files) {
                    helper.addAttachment(file.getName(), file);
                }
            }

        } catch (MessagingException e) {
            log.error("发送邮件失败！格式问题。", e);
            throw new NCException("", "发送邮件失败！格式问题。");
        }
        mailSender.send(mimeMessage);
    }

}